/* eslint no-underscore-dangle: 0 */
import React, { Component } from 'react';
import IceContainer from '@icedesign/container';
import targetImg from '@/assects/images/targetimg.png';
import { Button } from '@alifd/next';
import { host } from '../../../../const';
import styles from './index.module.scss';

const CANVAS_WIDTH = 600;
const CANVAS_HEIGHT = 600;
const D_RADIUS = 300;// 圆环半径
const D_X = 0;// 原点修正偏差
const D_Y = 40;// 原点修正偏差

const centerX = CANVAS_WIDTH / 2 + D_X;// 坐标系中心x
const centerY = CANVAS_HEIGHT / 2 + D_Y;// 坐标系中心y

export default class mCanvas extends Component {
    constructor(props) {
        super(props);

        this.state = {
            drawPointList: [
                // ['02', '06', '01'],
                // ['02', '06', '02'],
                // ['02', '06', '03'],
                // ['02', '06', '04'],
                // ['02', '06', '05'],
                // ['02', '06', '06'],
                // ['02', '06', '07'],
                // ['02', '06', '08'],
                // ['02', '07', '01'],
                // ['02', '07', '02'],
                // ['02', '07', '03'],
                // ['02', '07', '04'],
                // ['02', '07', '05'],
                // ['02', '07', '06'],
                // ['02', '07', '07'],
                // ['02', '07', '08'],
            ], // 要画的点
        };
        this.init = this.init.bind(this);
        this.drawBgImg = this.drawBgImg.bind(this);
        this.drawPoint = this.drawPoint.bind(this);
        this.countPoint = this.countPoint.bind(this);
        this.handleSocket = this.handleSocket.bind(this);
        this.clearScreen = this.clearScreen.bind(this);
    }

    componentDidMount() {
        this.init();
    }

  init = async () => {
      await this.drawBgImg();
      this.handleSocket();
  }

  handleSocket() {
      const wsUrl = `ws://${host.substr(7)}/socket`;
      const ws = new WebSocket(wsUrl);
      ws.onopen = () => {
          this.setState({
              drawPointList: [],
          });
      };
      ws.onmessage = (msg) => {
          const msgJson = JSON.parse(msg.data);
          if (msgJson?.data?.status == 2) {
              const drawPointList = [...this.state.drawPointList];
              const mockString = msgJson?.data?.msg;
              // let mockString = "03 08 02"
              const point = mockString.split(' ');
              drawPointList.push(point);
              const direction = this.getDirection(point);
              // 语音播报，兼容性待考究
              if (Number(point[2]) === 0) {
                  const utterThis = new window.SpeechSynthesisUtterance(`${point[0]}号,十环,神枪手`);
                  window.speechSynthesis.speak(utterThis);
              } else {
                  const utterThis = new window.SpeechSynthesisUtterance(`${point[0]}号,${point[1]}环,${direction}`);
                  window.speechSynthesis.speak(utterThis);
              }
              drawPointList.forEach((item) => {
                  const point2 = this.countPoint(Number(item[1]), Number(item[2]));
                  this.drawPoint(point2.x, point2.y, 10, 'red', item[0]);
              });
              this.setState({
                  drawPointList,
              });
          }
      };

      ws.onclose = () => {
          this.setState({
              drawPointList: [],
          });
      };
  }
  // 获取方位
  getDirection = (point) => {
      const no = point[2];
      let str = '';
      if (Number(no) === 1) {
          str = '偏上';
      }
      if (Number(no) === 2) {
          str = '偏右上';
      }
      if (Number(no) === 3) {
          str = '偏右';
      }
      if (Number(no) === 4) {
          str = '偏右下';
      }
      if (Number(no) === 5) {
          str = '偏下';
      }
      if (Number(no) === 6) {
          str = '偏左下';
      }
      if (Number(no) === 7) {
          str = '偏左';
      }
      if (Number(no) === 8) {
          str = '偏左上';
      }
      return str;
  }
  // 获取随机点
  getRandomPoint({ x, y }, radius) {
      const result = { x, y };
      const isPlus = !!Math.round(Math.random());

      result.x = isPlus ? result.x + Math.floor(Math.random() * radius) : result.x - Math.floor(Math.random() * radius);
      result.y = isPlus ? result.y + Math.floor(Math.random() * radius) : result.y - Math.floor(Math.random() * radius);
      return result;
  }
  // no成绩
  // direction正上方开始顺时针12345678

  countPoint(no, direction) {
      let x = 0;
      let y = 0;
      const middle = D_RADIUS / 5 / 2;// 修正到环中间
      const radius = (10 - no) * (D_RADIUS / 5) + middle;

      switch (direction) {
      case 0:
          x = 0;
          y = 0;
          break;
      case 1:
          x = 0;
          y = -radius;
          break;
      case 2:
          x = radius / Math.sqrt(2);
          y = -radius / Math.sqrt(2);
          break;
      case 3:
          x = radius;
          y = 0;
          break;

      case 4:

          x = radius / Math.sqrt(2);
          y = radius / Math.sqrt(2);
          break;

      case 5:
          x = 0;
          y = radius;
          break;
      case 6:
          x = -radius / Math.sqrt(2);
          y = radius / Math.sqrt(2);
          break;
      case 7:
          x = -radius;
          y = 0;
          break;
      case 8:
          x = -radius / Math.sqrt(2);
          y = -radius / Math.sqrt(2);
          break;
      default:
          break;
      }

      const degree = 20;
      if (direction === 2 && (no === 6 || no === 7)) { // 右上空白处特殊处理
          x = radius * Math.sin(degree * 2 * Math.PI / 360); y = -radius * Math.cos(degree * 2 * Math.PI / 360);
      }
      if (direction === 8 && (no === 6 || no === 7)) { // 右上空白处特殊处理
          x = -radius * Math.sin(degree * 2 * Math.PI / 360); y = -radius * Math.cos(degree * 2 * Math.PI / 360);
      }
      if (direction === 5 && no === 6) { // 正下边特殊处理
          x = 0;
          y = radius - middle / 2;
      }
      return { x, y };
  }
  drawBgImg = () => new Promise((resolve) => {
      const img = new Image();
      img.src = targetImg;
      const ctx = this.getCtx();
      img.onload = function () {
          ctx.drawImage(img, 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
          ctx.translate(centerX, centerY);
          resolve();
      };
  })

  translateCenter = () => {

  }

  getCtx = () => {
      const c = document.getElementById('mycanvas');
      const ctx = c.getContext('2d');
      return ctx;
  }


  // xNumber
  // 圆弧对应的圆心横坐标。
  // yNumber
  // 圆弧对应的圆心纵坐标。
  // radiusNumber
  // 圆弧的半径大小。
  // startAngleNumber
  // 圆弧开始的角度，单位是弧度。
  // endAngleNumber
  // 圆弧结束的角度，单位是弧度。
  // color（可选）Boolean
  // 填充的颜色
  // 弧度的开始到结束的绘制是按照顺时针来算，还是按时逆时针来算。如何设置为true，则表示按照逆时针方向从startAngle绘制到endAngle。

  drawPoint = (x, y, radius, color, text) => new Promise((resolve) => {
      const ctx = this.getCtx();
      ctx.beginPath();
      ctx.arc(x, y, radius, 0, Math.PI * 2, true);
      ctx.closePath();
      ctx.fillStyle = color;
      ctx.fill();
      ctx.fillStyle = '#ffffff';
      ctx.fillText(text, x - 5, y + 5);
      // 登录状态下不会出现这行文字，点击页面右上角一键登录
      resolve();
  })
  clearScreen = async () => {
      const ctx = this.getCtx();
      ctx.translate(-centerX, -centerY);
      ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
      await this.drawBgImg();
  }
  handlePoint = async () => {
      const pointList = [
          [10, 1],
          [9, 2],
          [9, 3],
          [9, 4],
          [9, 5],
          [9, 6],
          [7, 4],
          [9, 8],
      ];
      for (let i = 0; i < 3; i++) {
          pointList.push([Math.floor(Math.random() * 10), Math.floor(Math.random() * 9)]);
      }
      pointList.forEach((item, index) => {
          const point = this.countPoint(item[0], item[1]);
          // point = this.getRandomPoint(point, 10)
          this.drawPoint(point.x, point.y, 10, 'red', index);
      });
  }
  render() {
      return (
          <div className="filter-table">

              <IceContainer>
                  <div className={styles.wrap} >
                      <canvas id="mycanvas" className={styles.mycanvas} width={CANVAS_WIDTH} height={CANVAS_HEIGHT}>
              Your browser does not support the canvas element.

                      </canvas>
                      <div>
                          <div className={styles.btnWrap} >
                              <Button onClick={this.clearScreen} type="primary" className="mr" >
                  清屏
                              </Button>
                              {/* <Button onClick={this.handlePoint} type="primary">
                  加点
                </Button> */}
                          </div>

                      </div>
                  </div>


              </IceContainer>
          </div>
      );
  }
}
